import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { api } from '@/http/api'

export interface ChatMessage {
  type: 'user' | 'bot'
  content: string
}

export const useChatStore = defineStore('chat', () => {
  /**
   * 聊天记录
   * */
  // 创建一个引用，用于存储当前对话内容
  const chatHistory = ref<ChatMessage[]>([
    {
      type: 'bot',
      content: '请输入你的问题，例如：'
    },
    {
      type: 'bot',
      content: '你叫什么名字？'
    },
    {
      type: 'bot',
      content: '你知道谈判是干什么的吗？'
    }
  ])
  // 计算属性，获取当前对话内容
  const getChatHistory = computed(() => chatHistory.value)
  // 添加对话内容
  let addChatHistory = (message: ChatMessage) => {
    chatHistory.value = []
    addChatHistory = (message: ChatMessage) => {
      chatHistory.value.push(message)
    }
    addChatHistory(message)
  }
  /**
   * 聊天
   * */
  // 聊天控制器
  let chatController: AbortController | null = null
  // 聊天机器人
  const chatBot = (
    content: string,
    role: string = 'user',
    func = (res: any) => {
      console.log(res)
    }
  ): boolean => {
    if (chatController !== null) return false
    chatController = new AbortController()
    addChatHistory({
      type: 'user',
      content
    })
    api
      .post('/chat', {
        role,
        content
      })
      .then((res) => {
        addChatHistory({
          type: 'bot',
          content: res.data.content
        })
        cancelChatBot()
        if (func) {
          func(res) // 调用回调函数
        }
      })
    return true
  }
  // 取消本轮聊天
  const cancelChatBot = () => {
    if (chatController !== null) {
      chatController.abort()
      chatController = null
    }
  }
  // 清空聊天内容
  const clearChatHistory = () => {
    api.post('/clear_history').then(() => {
      chatHistory.value = []
    })
  }
  return { getChatHistory, chatBot, cancelChatBot, clearChatHistory }
})
